from datetime import datetime
from google.appengine.api import memcache
from google.appengine.ext import db
from plzkeepthat.common import constants as app
from plzkeepthat.models.models import NoteList, NoteOwner


#===============================================================================
# Utils for all classes
#===============================================================================

def get_notelist(user):
    """ Retrieves the notelist for the given user. """
    
    nl = memcache.get(user.user_id())
    if nl is not None:
        return nl

    q = db.Query(NoteOwner).filter('owner =', user.user_id())
    result = q.get()

    if not result:
        nl = init_new(user)
    else:
        nl = result.notes
    memcache.add(key = user.user_id(), value = nl, time = app.CACHETIME)
    return nl

def init_new(user):
    """ Initializes a new notelist for the specified user. """
    
    nl = NoteList(created = datetime.now(), name = user.nickname(), count = 0)
    nl.put()
    o = NoteOwner(owner = user.user_id(), notes = nl)
    o.put()
    return nl
    

